package com.demo.core.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.demo.base.cons.SessionKeyConstant;
import com.demo.base.model.UserInfo;
import com.demo.base.util.RequestContextHolderUtil;
import com.demo.base.util.StringUtil;
import com.demo.base.util.UUIDGenerator;
import com.demo.core.web.SessionContext;

public abstract class BaseController {

	/**
	 * 注销用户
	 * @param sid
	 */
	@SuppressWarnings("unchecked")
	protected void logOut(String sid) {
		HttpSession session = RequestContextHolderUtil.getSession();
		Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) session.getAttribute(SessionKeyConstant.SESSION_CONTEXT);
		if (map == null) {
			map = new HashMap<String, Map<String, Object>>();
		}
		Map<String, Object> m = map.get(SessionKeyConstant.USER_CONTEXT);
		if (m == null) {
			m = new HashMap<String, Object>();
		}
		m.remove(sid);
	}

	/**
	 * 获取保存在Session中的对象
	 * @return
	 */
	protected Object getSessionObj(String key) {
		return SessionContext.getSessionObj(key);
	}

	/**
	 * 获取保存在Session中的登录人员信息
	 * @return
	 */
	protected UserInfo getSessionUser() {
		return (UserInfo) this.getSessionObj(SessionKeyConstant.USER_CONTEXT);
	}




	/**
	 * 保存对象到Session中
	 * @param user
	 */
	@SuppressWarnings("unchecked")
	protected String setSessionObj(String key, Object obj) {
		HttpSession session = RequestContextHolderUtil.getSession();
		Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) session.getAttribute(SessionKeyConstant.SESSION_CONTEXT);
		if (map == null) {
			map = new HashMap<String, Map<String, Object>>();
		}
		String sid = UUIDGenerator.getUUID();
		Map<String, Object> m = map.get(key);
		if (m == null) {
			m = new HashMap<String, Object>();
		}
		m.put(sid, obj);
		map.put(key, m);
		session.setAttribute(SessionKeyConstant.SESSION_CONTEXT, map);
		return sid;
	}

	/**
	 * 更新session
	 * @param key
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected String updateSessionObj(String key, Object obj) {
		HttpSession session = RequestContextHolderUtil.getSession();
		Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) session.getAttribute(SessionKeyConstant.SESSION_CONTEXT);
		if (map == null) {
			map = new HashMap<String, Map<String, Object>>();
		}
		String sid = this.getSid();
		Map<String, Object> m = map.get(key);
		if (m == null) {
			m = new HashMap<String, Object>();
		}
		m.put(sid, obj);
		map.put(key, m);
		session.setAttribute(SessionKeyConstant.SESSION_CONTEXT, map);
		return sid;
	}

	/**
	 * 获取SID，如果为NULL 返回空字符
	 * @return
	 */
	protected String getSid() {
		HttpServletRequest request = RequestContextHolderUtil.getRequest();
		return StringUtil.delNull(request.getParameter("sid"));
	}

}
